package controllers

import (
	"encoding/base64"
	"encoding/json"
	"slotGame/models"
	"slotGame/utils"
	"strconv"
	"time"

	"github.com/astaxie/beego"
	"github.com/astaxie/beego/httplib"
	"github.com/astaxie/beego/orm"
	"github.com/bitly/go-simplejson"
)

//  CoinController oprations for Coin
type CoinController struct {
	beego.Controller
}

// URLMapping ...
func (c *CoinController) URLMapping() {
	c.Mapping("Post", c.AddMunis)
	c.Mapping("GetOne", c.CheckCoin)
}

// AddMunis ...
// @Title AddMunis
// @Description AddMunis Coin
// @Param	body		body 	models.Coin	true		"body for AddMunis Coin content"
// @Success 201 提交成功
// @Failure 403 body is empty
// @router / [post]
func (c *CoinController) AddMunis() {
	// AddMunisCoin(1, "示例游戏1", "3unjki37fm2nktd2blq69dm152")
	var v models.Coin
	var base64Str string

	json.Unmarshal([]byte(c.Ctx.Input.RequestBody), &v)
	st := time.Now().Unix()

	stringTime := strconv.FormatInt(st, 10)

	strKey := v.Game + v.Sid + stringTime
	key := utils.GetMd5FromString(strKey) //md5加密32位

	cMap := map[string]string{"game": v.Game, "amount": strconv.Itoa(v.Amount), "key": key}
	postMap, _ := json.Marshal(cMap)

	//	httplib.Post(beego.AppConfig.String("add_munis_coin"))

	//	var r rsa.RsaDecrypt
	if data, err := utils.RsaEncrypt([]byte(string(postMap))); err == nil {

		base64Str = base64.StdEncoding.EncodeToString(data)

		req := httplib.Post(beego.AppConfig.String("add_munis_coin") + v.Sid).Body(base64Str)
		// beego.Debug(base64Str)
		// req.Param("data", base64Str)

		str, err := req.String()
		debase64, _ := base64.StdEncoding.DecodeString(str)
		deRsa, _ := utils.RsaDecrypt(debase64)

		js, _ := simplejson.NewJson([]byte(deRsa))
		bolB, _ := json.Marshal(js)

		s, err := js.Get("code").Int()
		if err == nil {

		}
		if s == 0 {
			out := utils.Reponse(200, nil, "Success", nil)
			c.Data["json"] = out

		} else {
			o := orm.NewOrm()
			coinLog := new(models.CoinLog)
			coinLog.Sid = v.Sid
			coinLog.Result = "支付失败"
			// coinLog.Content = map[string]string{"aaa": "dd"}
			coinLog.Content = string(bolB)
			o.Insert(coinLog)
			out := utils.Reponse(403, nil, "fail", nil)
			c.Data["json"] = out

		}

		if err != nil {
			beego.SetLogger("file", `{"filename":"log/coin.log"}`)
		}

		// out := utils.Reponse(200, nil, "Success", nil)

		c.ServeJSON()

	} else {

		beego.SetLogger("file", `{"filename":"log/coin.log"}`)

	}

}

// CheckCoin ...
// @Title Check Coin
// @Description get User by sid
// @Param	sid		path 	string	true		"The key for staticblock"
// @Success 200 返回成功
// @Failure 401 :请重新登录
// @router /:id [get]
func (c *CoinController) CheckCoin() {
	idStr := c.Ctx.Input.Param(":id")
	// id, _ := strconv.Atoi(idStr)
	rep := httplib.Get(beego.AppConfig.String("check_coin") + idStr)
	resString, err := rep.String()
	if err != nil {
		beego.SetLogger("file", `{"filename":"log/check_coin.log"}`)
	} else {
		decodeBase64, bErr := base64.StdEncoding.DecodeString(resString)
		if bErr == nil {
			origgData, oErr := utils.RsaDecrypt(decodeBase64)
			if oErr == nil {
				var v models.CheckCoin
				// b := json.Marshal(origgData, &c)
				err := json.Unmarshal(origgData, &v)
				if v.Code != 0 { //code 新城猫接口登陆返回Code为0   登陆 成功
					out := utils.Reponse(401, nil, "请重新登陆", "sid无效")
					c.Data["json"] = out
				} else {
					if err == nil {
						beego.SetLogger("file", `{"filename":"log/check_coin.log"}`)

					} else {
						beego.SetLogger("file", `{"filename":"log/check_coin.log"}`)
					}
					out := utils.Reponse(200, map[string]float64{"coin": v.Result.Balance}, "Success", nil)

					c.Data["json"] = out
					c.ServeJSON()
				}

			} else {
				beego.SetLogger("file", `{"filename":"log/check_coin.log"}`)
			}

		} else {
			beego.SetLogger("file", `{"filename":"log/check_coin.log"}`)
		}
	}

	c.ServeJSON()
}

func GetUserCoin(sid string) (coin_num float64, err error) {
	coin_num = float64(-1)
	rep := httplib.Get(beego.AppConfig.String("check_coin") + sid)
	resString, err := rep.String()
	beego.Debug("getusercoin:", resString)
	if err != nil {

		beego.SetLogger("file", `{"filename":"log/check_coin.log"}`)
	} else {
		decodeBase64, bErr := base64.StdEncoding.DecodeString(resString)
		if bErr == nil {
			origgData, oErr := utils.RsaDecrypt(decodeBase64)
			if oErr == nil {
				var v models.CheckCoin
				// b := json.Marshal(origgData, &c)
				err := json.Unmarshal(origgData, &v)
				if v.Code != 0 { //code 新城猫接口登陆返回Code为0   登陆 成功
					//fmt.Println("coin_num:444")
					coin_num = float64(-1)
				} else {
					if err == nil {
						beego.SetLogger("file", `{"filename":"log/check_coin.log"}`)

					} else {
						beego.SetLogger("file", `{"filename":"log/check_coin.log"}`)
					}

					coin_num = v.Result.Balance

				}

			} else {

				beego.SetLogger("file", `{"filename":"log/check_coin.log"}`)
			}

		} else {

			beego.SetLogger("file", `{"filename":"log/check_coin.log"}`)
		}
	}
	return
}
